<template>
    <div>
        <el-card style="margin: 20px;border-radius: 20px;position: relative;min-height: 200px;">
            <div slot="header" class="clearfix">
                <span>基础配置</span>
                <el-button @click="onSubmit()" type="primary" size="medium"
                    style="position: absolute;top: 20px;right: 30px">保存
                </el-button>
            </div>
            <el-form ref="config-form" :inline="true" :model="data" label-width="100px" class="demo-ruleForm"
                size="small" label-position="left">
                <el-tabs v-model="activeTab" type="border-card" @tab-click="tabClick">
                    <el-tab-pane v-for="(config, key) in configs" :key="key" :label="config.label" :name="key">
                        <!-- <input v-if="config.fileInput" type="file" class="select-file"
                @change="handleFileInput($event, config.type)"> -->
                        <template v-if="config.table">
                            <el-table v-if="key != 'frontPage'" :data="data[config.dataKey]" stripe>
                                <el-table-column v-for="(column, colKey) in config.columns" :key="colKey"
                                    :label="column.label">
                                    <template slot-scope="scope">
                                        <el-input v-if="column.input" v-model="scope.row[column.input]"
                                            :disabled="column.disabled" :placeholder="column.placeholder"></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column label="操作">
                                    <template slot-scope="scope">
                                        <el-button type="text" @click="deleteRow(scope.$index, config.type)"
                                            style="color: red;">删除</el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                            <!-- 模板配置 -->
                            <template v-else>
                                <div style="color: red;margin: 10px 0;"> 默认第一个模板配置是首页，第二个模板是发现页</div>
                                <table stripe row-key="id" style="width: 80%;">
                                    <draggable v-model="data[config.dataKey]" tag="tbody" handle=".drag-handle"
                                        animation="300" class="dragArea list-group" ghost-class="sortable-ghost"
                                        :force-fallback="true">
                                        <tr v-for="(row, index) in data[config.dataKey]" :key="row.id">
                                            <td class="drag-handle" style="cursor: move;width: 50px;">
                                                <img src="@/assets/imgs/move.png" style="height: 30px;" />
                                            </td>
                                            <td v-for="(column, colKey) in config.columns" :key="colKey">
                                                <el-input v-if="column.input" v-model="row[column.input]"
                                                    :disabled="column.disabled"
                                                    style="background-color: white !important;"
                                                    :placeholder="column.placeholder"></el-input>
                                                <span v-else>{{ row[column.prop] }}</span>
                                            </td>
                                            <td>
                                                <el-button type="text" @click="goConfig(row)">去配置</el-button>
                                                <el-button type="text" @click="deleteConfig(row)"
                                                    v-if="index !== 0 && index !== 1" style="color: red;">删除</el-button>
                                            </td>
                                        </tr>
                                    </draggable>
                                </table>
                            </template>


                            <el-button type="primary" plain @click="addRow(config.type)"
                                style="margin-top: 20px;">+添加行</el-button>
                        </template>
                        <!-- 恢复公告配置 -->
                        <template v-else-if="key === 'ordertice'">
                            <el-row>
                                <el-col>
                                    <el-form-item label="公告内容:" style="width: 100%;">
                                        <el-input v-model="data.ordertice.content" type="textarea" :rows="4"
                                            style="width: 100%;" placeholder="请输入公告内容"></el-input>
                                    </el-form-item>
                                </el-col>
                            </el-row>
                            <el-row>
                                <el-col>
                                    <el-form-item label="是否启用:" label-width="150px">
                                        <el-switch v-model="data.ordertice.status" active-color="#13ce66"
                                            inactive-color="#cccccc" size="big" />
                                    </el-form-item>
                                </el-col>
                            </el-row>
                        </template>
                    </el-tab-pane>
                </el-tabs>
            </el-form>
        </el-card>
        <el-dialog title="同步OSS文件" :visible.sync="syncOss.show" width="400px">
            <el-form ref="oeprForm" :model="syncOss" label-width="100px">
                <el-form-item label="秘钥" prop="password" style="margin-top:10px">
                    <el-input style="width: 100%" type="password" v-model="syncOss.password" placeholder="请输入秘钥" />
                </el-form-item>
                <div style="margin-top: 20px;text-align: center">
                    <el-button type="success" @click="onSyncOssFile()">提交</el-button>
                </div>
            </el-form>
        </el-dialog>
    </div>
</template>

<script>
import { baseConfig, setBaseConfig, syncOssFile,vipConfig } from '@/api/baseConfig'
import vuedraggable from 'vuedraggable';
export default {
    name: "BaseConfig",
    components: {
        draggable: vuedraggable,
    },
    data() {
        return {
            activeTab: 'vip', // 默认激活的标签页
            syncOss: {
                show: false,
                password: ""
            },
            data: {
                // vip
                vipRows: [
                    { amount: '', download: '', time: '', name: "", id: "" } // 初始行数据
                ],
                promotionGrade: [
                    { id: "", grade: "", num: "", time: "", cacheTimes: "" }
                ],
                frontPage: [
                    { id: 1, name: "推荐" },
                    { id: 2, name: "发现" },
                ],
                payConfig: [
                    { id: "", amount: "", desc: "" }
                ],
                acting1: [
                    { id: "", lrMax: "", lrMin: "", hyNum: "", bl: "" }
                ],
                acting2: [
                    { id: "", lrMax: "", lrMin: "", hyNum: "", bl: "" }
                ],
                acting3: [
                    { id: "", lrMax: "", lrMin: "", hyNum: "", bl: "" }
                ],
                ordertice: {
                    content: "这是最新的公告配置！请注意查收！",
                    status: true
                },
                // 大小个数
                mvid: { max: "", min: "", bt: "" },
            },
            configs: {
                vip: {
                    label: 'VIP配置',
                    type: 1,
                    fileInput: true,
                    table: true,
                    dataKey: 'vipRows',
                    columns: {
                        id: { label: 'id', input: 'id', placeholder: '请输入id' },
                        name: { label: '名称', input: 'name', placeholder: '请输入名称' },
                        amount: { label: '金额', input: 'amount', placeholder: '请输入金额' },
                        download: { label: '下载次数', input: 'download', placeholder: '请输入下载次数' },
                        time: { label: '天数', input: 'time', placeholder: '请输入天数' },
                    }
                },
                promotion: {
                    label: '推荐配置',
                    type: 2,
                    fileInput: true,
                    table: true,
                    dataKey: 'promotionGrade',
                    columns: {
                        id: { label: 'id', input: 'id', placeholder: '请输入id' },
                        grade: { label: '等级', input: 'grade', placeholder: '请输入等级' },
                        num: { label: '邀请人数', input: 'num', placeholder: '请输入数目' },
                        time: { label: '天数', input: 'time', placeholder: '请输入天数' },
                        cacheTimes: { label: '缓存次数', input: 'cacheTimes', placeholder: '请输入' },
                    }
                },
                frontPage: {
                    label: '模板配置',
                    type: 3,
                    dataKey: 'frontPage',
                    fileInput: true,
                    table: true,
                    columns: {
                        id: { label: 'ID', input: 'id', placeholder: '请输入id', disabled: true },
                        name: { label: '模板名称', input: 'name', placeholder: '请输入模板名称' },
                    }
                },
                pay: {
                    label: '充值配置',
                    type: 4,
                    fileInput: true,
                    table: true,
                    dataKey: 'payConfig',
                    columns: {
                        id: { label: 'id', input: 'id', placeholder: '请输入id' },
                        name: { label: '描述', input: 'name', placeholder: '请输入描述' },
                        amount: { label: '金额', input: 'amount', placeholder: '请输入金额' },
                    }
                },
                acting1: {
                    label: '一级代理配置',
                    type: 5,
                    fileInput: true,
                    table: true,
                    dataKey: 'acting1',
                    columns: {
                        id: { label: 'id', input: 'id', placeholder: '请输入id' },
                        hyNum: { label: '活跃人数', input: 'hyNum', placeholder: '请输入活跃人数' },
                        lrMax: { label: '净利润>=（万元）', input: 'lrMax', placeholder: '请输入净利润' },
                        lrMin: { label: '净利润<（万元）', input: 'lrMin', placeholder: '请输入净利润' },
                        bl: { label: '佣金比例', input: 'bl', placeholder: '请输入佣金比例' },
                    }
                },
                acting2: {
                    label: '二级代理配置',
                    type: 6,
                    fileInput: true,
                    table: true,
                    dataKey: 'acting2',
                    columns: {
                        id: { label: 'id', input: 'id', placeholder: '请输入id' },
                        hyNum: { label: '活跃人数', input: 'hyNum', placeholder: '请输入活跃人数' },
                        lrMax: { label: '净利润>=（万元）', input: 'lrMax', placeholder: '请输入净利润' },
                        lrMin: { label: '净利润<（万元）', input: 'lrMin', placeholder: '请输入净利润' },
                        bl: { label: '佣金比例', input: 'bl', placeholder: '请输入佣金比例' },
                    }
                },
                acting3: {
                    label: '总级代理配置',
                    type: 7,
                    fileInput: true,
                    table: true,
                    dataKey: 'acting3',
                    columns: {
                        id: { label: 'id', input: 'id', placeholder: '请输入id' },
                        hyNum: { label: '活跃人数', input: 'hyNum', placeholder: '请输入活跃人数' },
                        lrMax: { label: '净利润>=（万元）', input: 'lrMax', placeholder: '请输入净利润' },
                        lrMin: { label: '净利润<（万元）', input: 'lrMin', placeholder: '请输入净利润' },
                        bl: { label: '佣金比例', input: 'bl', placeholder: '请输入佣金比例' },
                    }
                },
                ordertice: {
                    label: '公告配置',
                    custom: {
                        component: 'OrderticeConfig'
                    }
                },
            }
        }
    },
    created() {
        this.doGetBaseConfig();
        // this.getConfigTypes();
    },
    methods: {
        deleteConfig(row) {

            const type = this.activeTab;
            const index = this.data[type].findIndex(item => item.id === row.id);
            this.data[type].splice(index, 1)
        },
        goConfig(row) {
            const { href } = this.$router.resolve({
                path: `/creatDevise/${row.id}/${row.name}`,
            });
            // this.$router.push(href);
            window.open(href);
            // const newWindow = window.open(href, '_blank');
        },
        tabClick(e) {
            // console.log(e);
            if (e.name == "frontPage") { }
            // this.doGetBaseConfig()
        },
        // 获取数据
        doGetBaseConfig() {
            baseConfig().then(res => {
                if (res.status == 0) {
                    this.data = res.data || {};

                    if (!res.data || !this.data.vipRows) {
                        this.$set(this.data, "vipRows", [{}])
                    }
                    if (!res.data || !this.data.promotionGrade) {
                        this.$set(this.data, "promotionGrade", [{}])
                    }
                    if (!res.data || !this.data.frontPage) {
                        this.$set(this.data, "frontPage", [])
                    }
                    if (!res.data || !this.data.payConfig) {
                        this.$set(this.data, "payConfig", [{}])
                    }
                    if (!res.data || !this.data.acting1) {
                        this.$set(this.data, "acting1", [{}])
                    }
                    if (!res.data || !this.data.acting2) {
                        this.$set(this.data, "acting2", [{}])
                    }
                    if (!res.data || !this.data.acting3) {
                        this.$set(this.data, "acting3", [{}])
                    }
                    if (!res.data || !this.data.ordertice) {
                        this.$set(this.data, "ordertice", { content: "", status: true })
                    }
                    // console.log(111111111, this.data);
                }
            })
        },
        /**
         * 操作
         * @param key
         * @param type
         * @param k
         * @param index
         */
        onOper(key, type, k, index) {
            if (key === "del") {
                this.data[type][k].splice(index, 1)
            } else {
                if (k === "types" || k === "searchs") {
                    this.data[type][k].push("")
                } else {
                    this.data[type][k].push({
                        img: "",
                        href: "",
                        name: ""
                    })
                }
            }
        },
        onSubmit() {
            let param = {
                ...this.data,
                ordertice: {
                    content: this.data.ordertice.content,
                    status: this.data.ordertice.status,
                }
            }

            console.log('保存参数', param);

            // return
            setBaseConfig({ config: param }).then(res => {
                if (res.status === 0) {
                    this.$message.success(res.msg)
                    this.doGetBaseConfig();
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        // 同步oss文件
        onSyncOssFile() {
            if (!this.syncOss.password) {
                this.$message.success("请输入秘钥！");
                return;
            }
            let loadding = this.openLoading();
            syncOssFile({ password: this.syncOss.password }).then(res => {
                if (res.status === 0) {
                    this.syncOss = {
                        show: false,
                        password: ""
                    }
                    this.$message.success(res.msg)
                } else {
                    this.$message.error(res.msg)
                }
            }).finally(() => {
                loadding.close();
            })
        },
        // 添加行的方法
        addRow(type) {
            const newRow = {
                id: "",
                name: "",
                amount: "",
                download: "",
                time: "",
                grade: "",
                num: "",
                cacheTimes: "",
                hyNum: "",
                lrMax: "",
                lrMin: "",
                bl: "",
            };
            switch (type) {
                case 1:
                    this.data.vipRows.push({ ...newRow, amount: '', download: '', time: '', name: "", id: "" });
                    break;
                case 2:
                    this.data.promotionGrade.push({ ...newRow, id: "", grade: "", num: "", time: "", cacheTimes: "" });
                    break;
                case 3:
                    this.data.frontPage.push({ id: new Date().getTime(), name: "" });
                    break;
                case 4:
                    this.data.payConfig.push({ ...newRow, id: "", amount: "", desc: "" });
                    break;
                case 5:
                    this.data.acting1.push({ ...newRow, id: "", lrMax: "", lrMin: "", hyNum: "", bl: "" });
                    break;
                case 6:
                    this.data.acting2.push({ ...newRow, id: "", lrMax: "", lrMin: "", hyNum: "", bl: "" });
                    break;
                case 7:
                    this.data.acting3.push({ ...newRow, id: "", lrMax: "", lrMin: "", hyNum: "", bl: "" });
                    break;
            }
        },
        // 删除行的方法
        deleteRow(index, type) {
            switch (type) {
                case 1:
                    if (this.data.vipRows.length > 1) {
                        this.data.vipRows.splice(index, 1);
                    }
                    break;
                case 2:
                    if (this.data.promotionGrade.length > 1) {
                        this.data.promotionGrade.splice(index, 1);
                    }
                    break;
                case 3:
                    if (this.data.frontPage.length > 1) {
                        this.data.frontPage.splice(index, 1);
                    }
                    break;
                case 4:
                    if (this.data.payConfig.length > 1) {
                        this.data.payConfig.splice(index, 1);
                    }
                    break;
                case 5:
                    if (this.data.acting1.length > 1) {
                        this.data.acting1.splice(index, 1);
                    }
                    break;
                case 6:
                    if (this.data.acting2.length > 1) {
                        this.data.acting2.splice(index, 1);
                    }
                    break;
                case 7:
                    if (this.data.acting3.length > 1) {
                        this.data.acting3.splice(index, 1);
                    }
                    break;
            }
        },
        // 提交表单的方法
        submitForm() {
            let loadding = this.openLoading();
            loadding.close();
            this.vipButton = false;
            vipConfig({ vip: this.data.vipRows }).then(res => {
                if (res.status === 0) {
                    this.$message.success(res.msg)
                    // this.doGetBaseConfig();
                } else {
                    this.$message.error(res.msg)
                }
            })
        },
        handleFileInput(event, type) {
            const file = event.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = (e) => {
                    try {
                        const jsonData = JSON.parse(e.target.result);
                        if (Array.isArray(jsonData)) {
                            switch (type) {
                                case 1:
                                    this.data.vipRows = jsonData;
                                    break;
                                case 2:
                                    this.data.promotionGrade = jsonData;
                                    break;
                                case 3:
                                    this.data.frontPage = jsonData;
                                    break;
                                case 4:
                                    this.data.payConfig = jsonData;
                                    break;
                                case 5:
                                    this.data.acting1 = jsonData;
                                    break;
                                case 6:
                                    this.data.acting2 = jsonData;
                                    break;
                                case 7:
                                    this.data.acting3 = jsonData;
                                    break;
                            }
                        } else {
                            console.error('导入的 JSON 文件不是有效的数组格式。');
                        }
                    } catch (error) {
                        console.error('解析 JSON 文件时出错:', error);
                    }
                };
                reader.readAsText(file);
            }
        }
    }
}
</script>
<style scoped lang="scss">
::v-deep .el-input.is-disabled .el-input__inner {
    background-color: #fff;
    color: black;
}

::v-deep .el-form-item--small .el-form-item__content {
    width: 80%;
}

::v-deep .el-form-item--small.el-form-item {
    display: flex;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
}

.avatar {
    width: 100px;
    height: 100px;
    display: block;
}

.dragArea.list-group {
    // display: grid;
    // grid-template-columns: repeat(2, 1fr);
    // // overflow-y: scroll;
    // overflow-x: hidden;

    .list-group-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 74px;
        margin-right: 17px;
        margin-bottom: 34px;
        font-size: 12px;
        color: #666;
        cursor: pointer;
        border-radius: 5px;
        text-align: center;

        &:hover {
            box-shadow: 0 0 5px 0 rgba(24, 144, 255, 0.3);
            border-right: 5px;
        }

        &:nth-child(3n) {
            margin-right: 0;
        }
    }
}
</style>